﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.HandInvoice.Dto;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Engine;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Utils;
using NP.Enterprise.Utils.Http;
using SqlSugar;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.HandInvoice
{
    public class HandInvoiceService : BPMReportPlatformAppService, IHandInvoiceService
    {
        private readonly SqlSugarClient _db, _dbPlatform, _dbProcess, _dbEngine;
        private readonly INPRestHttpHelper _httpClient;
        private readonly IBPMUtilsAppService _bPmUtilsApp;
        private readonly IBPMPlatformAppService _iBpmPlatformApp;

        private readonly string _esbUrl;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="sqlSugarAppService"></param>
        /// <param name="httpClient"></param>
        /// <param name="configuration"></param>
        /// <param name="bPmUtilsApp"></param>
        /// <param name="iBpmPlatformApp"></param>
        public HandInvoiceService(ISqlSugarAppService sqlSugarAppService, INPRestHttpHelper httpClient, IConfiguration configuration, IBPMUtilsAppService bPmUtilsApp, IBPMPlatformAppService iBpmPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _dbProcess = sqlSugarAppService.GetProcessInstance();
            _dbEngine = sqlSugarAppService.GetEngineInstance();
            _httpClient = httpClient;
            _esbUrl = configuration["Nippon:ESB:ESBCommApi"];
            _bPmUtilsApp = bPmUtilsApp;
            _iBpmPlatformApp = iBpmPlatformApp;
        }


        public async Task<PagedResultDto<GetHandInvoiceOutput>> GetAllAsync(GetHandInvoiceInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBpmPlatformApp.GetUserAsync(CurrentUser.UserName);
            listViewDto.ForEach(x => { x.Url = _bPmUtilsApp.GetProcessUrl(x.InstanceNumber, userId); });
            listViewDto.ForEach(x => { x.InvoiceCompany = x.InvoiceCompanyCode + "-" + x.InvoiceCompany; });
            //返回结果
            return new PagedResultDto<GetHandInvoiceOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetHandInvoiceOutput>> ExportAsync(GetHandInvoiceInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }

        public ISugarQueryable<GetHandInvoiceOutput> GetQueryable(GetHandInvoiceInput input)
        {
            var listQueryable = _db.Queryable<RedRushApplication, RedRushManualInvoice, BusinessProcessesNew>(
                (a, b, c) => a.InstanceNumber == b.InstanceNumber && a.InstanceNumber == c.InstanceId)

            .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                (a, b, c) => a.InstanceNumber == input.InstanceNumber)
            .WhereIF(!input.Flowstate.IsNullOrEmpty(),
                (a, b, c) => SqlFunc.ContainsArray(input.Flowstate.ToArray(), c.ProcessStatusCode))
            .WhereIF(input.beginTime.HasValue && input.endTime.HasValue, (a, b, c) => a.AddTime > input.beginTime && a.AddTime < input.endTime)
            .WhereIF(!string.IsNullOrEmpty(input.InvoiceCode), (a, b, c) => b.InvoiceCode.Contains(input.InvoiceCode))
            .WhereIF(!string.IsNullOrEmpty(input.InvoiceNo), (a, b, c) => b.InvoiceNo.Contains(input.InvoiceNo))
            .Select((a, b, c) => new GetHandInvoiceOutput()
            {
                InstanceNumber = a.InstanceNumber,
                ProcessStartUserName = c.StartUserName,
                Flowstate = c.ProcessStatusCode,
                ProcessStartTime = c.StartTime,
                InvoiceCode = b.InvoiceCode,
                Id = b.Id,
                RedRushTypeName = a.RedRushTypeName,
                InvoiceCompany = a.InvoiceCompany,
                InvoiceCompanyCode = a.InvoiceCompanyCode,
                InvoiceType = a.InvoiceTypeName,
                ApplicationTypeName = a.ApplicationTypeName,
                InvoiceSalesDepartmentName = a.InvoiceSalesDepartmentName,
                InvoiceAreaName = a.InvoiceAreaName,
                ChannelName = a.ChannelName,
                OriginOpportunityNo = a.OriginOpportunityNo,
                NewOpportunityNo = a.NewOpportunityNo,
                NewCustomName = a.NewCustomName,
                CustomCode = b.CustomCode,
                CustomerType = b.CustomType,
                CustomerName = b.CustomName,
                ApplicationContentName = b.ApplicationContentName,
                InvoiceContent = b.InvoiceContent,
                TaxRate = b.TaxRate.ToString(),
                TaxClassificationNo = b.TaxClassificationNo,
                Price = b.Price.ToString(),
                Quantity = b.Quantity.ToString(),
                TotalInvoice = b.TotalInvoice.ToString(),
                Remark = b.Remark,
                Tax = b.Tax.ToString(),
                TaxFreeAmount = b.TaxFreeAmount.ToString(),
                ProductGroup = b.ProductGroup,
                ItemNo = b.ItemNo,
                InvoiceDate = b.InvoiceDate.Value.ToString("yyyy-MM-dd"),
                InvoiceNo = b.InvoiceNo.ToString(),
                CertificateNo = b.CertificateNo,
                RecipientCertificateNo = b.RecipientCertificateNo,
                PYTRemark = b.PYTRemark ?? "",
                SAPVenderCode18 = b.SAPVenderCode18,
                SAPVenderCode2 = b.SAPVenderCode2,
                SAPVenderCode3 = b.SAPVenderCode3,
                CustomerPayment = b.CustomerPayment,
                IsPaymentCollection = b.IsPaymentCollection == true ? "是" : "否",
                ManualOrderNumber_X = b.ManualOrderNumber_X,
                IsVoucher = b.IsVoucher == true ? "是" : "否",
                IsHand = a.isHand == true ? "是" : "否",
            }).OrderBy(a => a.InstanceNumber, OrderByType.Desc);

            return listQueryable;

        }
    }
}